<template>
  <div class="app-container" @click="popupShow = false" v-loading="pageLoading" @click.stop="(calendarIndex = null)">

    <el-row :gutter="20" class="mb12">
      <el-col :span="16">
        <div class="topTitle">
          <div class="top-title pd-r10 ">
            <span>形式历</span>
            <!-- <i class="pointer f18 text-blue" @click="topRightShowClick"
              :class="[!showRight?'el-icon-arrow-left':'el-icon-arrow-right']"></i> -->
          </div>
          <el-button type="primary" class="fr ml-20" @click="createItem">批量生成</el-button>
          <el-button type="danger" class="fr " @click="updateItem">批量调整</el-button>
          <div class="filter-container flex flex-center">
            <el-button :icon="Back" title="上一月" @click="queryMouthChange(false)"></el-button>
            <el-date-picker style="margin-right:0" format="YYYY-MM" value-format="YYYY-MM-01" :editable="false"
              :clearable="false" v-model="query.time" type="month" placeholder="选择月" @change="getList">
            </el-date-picker>
            <el-button :icon="Right" title="下一月" @click="queryMouthChange(true)">
            </el-button>
            <el-button type="success" plain @click="research">搜索</el-button>
          </div>

          <div class="calendar" v-loading="calendarLoading">
            <div class="calendar_header">
              <div class="calendar_item">一</div>
              <div class="calendar_item">二</div>
              <div class="calendar_item">三</div>
              <div class="calendar_item">四</div>
              <div class="calendar_item">五</div>
              <div class="calendar_item">六</div>
              <div class="calendar_item">日</div>
            </div>
            <div class="calendar_main">
              <div class="calendar_item" v-for="(item, index) in list" :key="index">
                <div v-if="item.isEmpty">

                </div>
                <div v-else class="calendar_item_base">
                  <!-- 顶部日期 -->
                  <div class="pd4 " style="font-weight:bolder"
                    :style="{ color: item.DateType == 'R' ? '#f56c6c' : '' }">
                    {{ dayjs(item.WorkDate).format('MM-DD') }}
                  </div>
                  <div class=" calendar_item_base_class " @mouseleave="calendarHoverIndex = null"
                    @click.stop="calendarClick(item.D, index, 0)"
                    :class="[calendarIndex == index && calendarType == 0 ? 'calendar_item_base_class_isClick' : '']">
                    <div v-if="item.DateType == 'W'" @mousemove="(calendarHoverIndex = index, calendarHoverType = 0)">
                      {{ item?.D?.ShiftCode }} [{{ (item?.D?.Hours / 60).toFixed(1) ??0}}H]
                    </div>

                  </div>
                  <div class=" calendar_item_base_class" @mouseleave="calendarHoverIndex = null"
                    @click.stop="calendarClick(item.N, index, 1)"
                    :class="[calendarIndex == index && calendarType == 1 ? 'calendar_item_base_class_isClick' : '']">
                    <div v-if="item.DateType == 'W'" @mousemove="(calendarHoverIndex = index, calendarHoverType = 1)">
                      {{ item?.N?.ShiftCode }}[{{ (item?.N?.Hours / 60).toFixed(1) ??0 }}H]
                    </div>

                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="8">
        <div class="topTitle">
          <div class="top-title pd-r10 ">
            <span>班次信息</span>
          </div>
          <div class="mb10 flex flex-row-end fr mb-10" v-if="row.ShiftId">
            <!-- <el-button type="primary" v-if="!(row&& row.Id)" @click="calendarClickSelect(0)">{{$ts('newly_added')}}
            </el-button> -->
            <el-button type="warning" @click="calendarClickSelect(1)">编辑</el-button>
            <el-popconfirm title="确定删除当前的班次信息吗？" @confirm="calendarClickSelect(2)">
              <template #reference>
                <el-button type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </div>


          <z-table :list="rightList" :tableProps="tableProps" :columns="leftColumns" v-loading="bRloading">
            <template v-slot:content="{ row, key }">
              <span v-if="key == 'ClockInType'">{{ ['正常上班', '休息', '加班'][row[key] - 1] }}</span>
              <span v-else-if="key == 'StartTime'" v-timeFormat="row[key]" format="HH:mm"></span>
              <span v-else-if="key == 'EndTime'" v-timeFormat="row[key]" format="HH:mm"></span>
              <span v-else> {{ row[key] }}</span>
            </template>
          </z-table>
        </div>
      </el-col>
    </el-row>

    <z-form-dialog :name="name" :data="data" :formProps="formProps" :fields="fields" @submit="submit"
      :submitLoading="submitLoading" v-model="editFormVisible"></z-form-dialog>

    <z-form-dialog :name="name" :data="data2" :formProps="formProps" :fields="fields2" @submit="submit2"
      :submitLoading="submitLoading" v-model="editFormVisible2"></z-form-dialog>
    <!-- <action-over-delete :loading="submitLoading" :name="actionsOverType==1?$ts('LineBodySwap'):$ts('BatchDelete')"
      :type="actionsOverType" v-model="editFormVisible3" @submit="submit3">
    </action-over-delete> -->

    <div class="popup-tooltip" :style="{
      top: popup.top + 'px',
      left: popup.left + 'px'
    }" v-show="popupShow">
      <template v-for="item in popupList">
        <div v-if="item.ishaveDate" class="popup-tooltip-item" @click="popupClick(item)" :key="item.title">
          {{ item.title }}</div>
      </template>
    </div>

  </div>
</template>


<script setup>
import {
  Back,
  Right
} from '@element-plus/icons-vue'
</script>
<script>
import commonMixin from '@/views/_common/mixin'
import dayjs from 'dayjs'
import ActionOverDelete from './components/actionOverDelete.vue'
import _, { multiply } from 'lodash'

export default {
  mixins: [commonMixin],
  components: {
    ActionOverDelete,
  },
  name: 'calendar',
  data: function () {
    return {
      updateFlag:false, // 调整行事历还是批量创建
      api: this.$api.calendar,
      apiCreate: this.$api.calendar + 'save',
      apiEdit: this.$api.calendar + 'save',
      name: '行事历',
      leftColumns: [
        { title: '类型', key: 'ClockInType' },
        { title: '开始时间', key: 'StartTime' },
        { title: '结束时间', key: 'EndTime' },
        { title: '工时(min)', key: 'Hours' },
      ],
      formProps: {
        dialogWidth: '70%',
        labelWidth: '140px',
        title:"行事历", //dialog title
      },
      rightColumns: [
        { title: '类型', key: 'ClockInType' },
        { title: '开始时间', key: 'StartTime' },
        { title: '结束时间', key: 'EndTime' },
        { title: '工时(min)', key: 'Hours' },
      ],
      fields: [

        {
          title: '白班',
          key: 'ScheduleId0',
          options: [],
          name: 'select',
          filterable: true,
          span: 7,
          props: {
            clearable: true,
          },
        },

        {
          title: '夜班',
          key: 'ScheduleId1',
          options: [],
          name: 'select',
          filterable: true,
          span: 7,
          props: {
            clearable: true,
          },
        },

        {
          title: '日期范围',
          key: 'dataTime',
          name: 'dateTime',
          required: true,
          props: {
            type: 'daterange',
            valueFormat: 'YYYY-MM-DD',
            rangeSeparator: '至',
            startPlaceholder: this.$ts('StartDate'),
            endPlaceholder: this.$ts('EndDate'),
          },
        },
        {
          title: '工作日',
          key: 'IsResult',
          name: 'switch',
          hidden: false,
          events:{change:this.changeIsResult}
        },
        {
          title: '跳过休息日',
          key: 'IsSkip',
          name: 'switch',
          hidden:false,
        },
        {
          title: '休息日',
          key: 'Weeks',
          name: 'checkboxGroup',
          hidden: false,
          options: [
            { label: '一', value: 1 },
            { label: '二', value: 2 },
            { label: '三', value: 3 },
            { label: '四', value: 4 },
            { label: '五', value: 5 },
            { label: '六', value: 6 },
            { label: '日', value: 0 },
          ],
        },
        {
          title: '工作设备(默认所有)',
          key: 'deviceIds',
          options: [],
          name: 'select',
          filterable: true,
          span: 12,
          hidden: true,
          props: {
            clearable: true,
            multiple:true,
            clearable:true
          },
        },
      ],

      fields2: [
        {
          title: '日期',
          key: 'WorkDate',
          props: {
            disabled: true,
          },
        },

        {
          title: '班次',
          key: 'ShiftId',
          options: [],
          filterable: true,
          name: 'select',
        },
      ],
      tableProps: {
        border: true,
        hideOperations: true,
        NOscrollBar: true,
      },
      query: {
        time: dayjs().format('YYYY-MM-01'),
      },
      dataUpdate:{},
      calendarLoading: false,
      leftList: [],
      rightList: [],
      bLloading: false,
      bRloading: false,
      editButtonShow: false,
      calendarIndex: null, // 白班0，夜班1
      calendarType: 0,
      calendarHoverIndex: null,
      calendarHoverType: 0,
      editFormVisible2: false,
      data2: {},
      rightQuery: {},
      editFormVisible3: false,
      actionsOverType: 1,

      popupShow: false,
      popup: {
        top: 0,
        left: 0,
        type: 0, //默认为白班右击
      },
      popupList: [
        { title: '新增', ishaveDate: false },
        { title: '编辑', ishaveDate: false },
        { title: '删除', ishaveDate: false },
      ],
      popupType: 0,
      popupData: {},

      showRight: true,
      initData: {
        Weeks: [],
        NLostRate: 100,
        DLostRate: 100,
      },
      row: {},
      showTitleName: true,
      foremanOptions: [],
    }
  },
  computed: {
    showRightSpan: {
      get() {
        if (!this.showRight) return this.showRight
        return setTimeout(() => {
          return this.showRight
        }, 500)
      },
    },
  },
  filters: {
    dataTime: function (val) {
      return dayjs(val).format('HH:mm')
    },
    hours: function (val) {
      return parseFloat(val / 60).toFixed(2)
    },
  },
  methods: {
    changeIsResult(v){
      let tmp = this.fields.find(i => i.key =='IsResult')
      tmp.title = !v ? '工作日':'休息日'
    },
    //
    createItem() {
      // this.setFieldsDisable(false, ['LineCode'])
      this.data = _.cloneDeep(this.initData)
      this.setForemanOptions()
      this.updateFlag = false
      this.editFormVisible = true
      let IsResult = this.fields.find(i => i.key =='IsResult')
      let IsSkip = this.fields.find(i => i.key =='IsSkip')
      let deviceIds = this.fields.find(i => i.key =='deviceIds')
      let Weeks = this.fields.find(i => i.key =='Weeks')
      IsResult.hidden = true
      IsSkip.hidden = false
     // deviceIds.hidden = false
      Weeks.hidden = false
    },
    async editItem(item, type) {
      // 调整班次，分白班夜班
      let ScheduleId0 = this.fields.find(i => i.key =='ScheduleId0')
      let ScheduleId1 = this.fields.find(i => i.key =='ScheduleId1')
     
      let Shift = this.fields2.find(i => i.key =='ShiftId')
      Shift.options = this.calendarType == 0 ? ScheduleId0.options:ScheduleId1.options
    
      this.editFormVisible2 = true
      this.data2.WorkDate = dayjs(item.WorkDate).format('YYYY-MM-DD')
      this.data2.ShiftId = item.ShiftId
      this.data2.PlantCalendarId = item.PlantCalendarId
    },
    calendarClick(row, index, type) {
      this.calendarIndex = index
      this.calendarType = type
      this.row = row ? _.cloneDeep(row) : {}

      this.editButtonShow = true
      if (row?.ShiftId) this.getScheduleList(row.ShiftId, this.calendarType)
      else this.rightList = []

      
    },
    checkDataFormat(day, arr) {
      let addDay = new Date(dayjs(day).valueOf()).getDay()
      let weekIndex = [1, 2, 3, 4, 5, 6, 0]
      let needAddList = weekIndex.findIndex((x) => addDay == x)
      let addArr = _.cloneDeep(arr)
      if (needAddList > 0) {
        for (let i = 0; i < needAddList; i++) {
          addArr.unshift({
            isEmpty: true,
          })
        }
      }
      return addArr
    },

    // 设定
    setForemanOptions() {
      this.setFieldOptions(
        'LineCode0',
        this.foremanOptions.filter(
          (x) => x.ForemanCode.indexOf(this.data.LineCode) != -1
        ),
        'Id',
        ['ForemanCode', 'ForemanName']
      )
      this.setFieldOptions(
        'LineCode1',
        this.foremanOptions.filter(
          (x) => x.ForemanCode.indexOf(this.data.LineCode) != -1
        ),
        'Id',
        ['ForemanCode', 'ForemanName']
      )
    },
    getForemanOptions() {
      this.http.post(this.$api.machine + 'GetPageData', {
        rows: 999,
      }).then(r=> {
        this.setFieldOptions('deviceIds', r.rows, 'MachineId', [
          'MachineCode',
          'MachineName',
        ])
      })

      this.http.post(this.$api.shift + 'GetPageData', {
        rows: 999,
      }).then((r) => {
        this.setFieldOptions('ScheduleId0', r.rows.filter(i => i.ShiftType == 0), 'ShiftId', [
          'ShiftCode',
          'ShiftName',
        ])
        this.setFieldOptions('ScheduleId1', r.rows.filter(i => i.ShiftType == 1), 'ShiftId', [
          'ShiftCode',
          'ShiftName',
        ])
      })

    },
    // 获取工时排版
    getScheduleList(id) {
      this.bRloading = true
      let data = {
        row:999,
        sort:'StartTime',
        order:"asc",
        wheres:JSON.stringify([{
          name: "ShiftId",
          value: id,
        }])
      }
      this.http.post(this.$api.shiftDetail + 'GetPageData', data)
        .then((r) => {
          this.rightList = r.rows
          this.bRloading = false
        })
        .catch(() => {
          this.bRloading = false
        })
    },
    formatBeforeSave(data) {
      let tmp = _.cloneDeep(data)
      // tmp.LineCode = tmp.LineCode ? tmp.LineCode : this.query.LineCode
      if (tmp.dataTime instanceof Array && tmp.dataTime.length == 2) {
        tmp.StartTime = tmp.dataTime[0]
        tmp.EndTime = tmp.dataTime[1]
      } else {
        tmp.StartTime = ''
        tmp.EndTime = ''
      }


      return tmp
    },
    formatList(list) {
      let tmp = _.cloneDeep(list)
      if(!tmp.length) return []
      let oldDataList = tmp.map((x) => x.WorkDate)
      let newDataList = new Set(oldDataList)
      console.log(list,'list')
      let dataList = Array.from(newDataList).map((x) => {
        return {
          WorkDate: x,
          DateType: tmp.find((c) => c.WorkDate == x).DateType,
          Hours: tmp.find((c) => c.WorkDate == x).Hours,
          ShiftCode: tmp.find((c) => c.WorkDate == x).ShiftCode,
          ShiftId: tmp.find((c) => c.WorkDate == x).ShiftId,
        }
      })
      for (let i = 0; i < dataList.length; i++) {
        let dayTmpList = tmp.filter((x) => x.WorkDate == dataList[i].WorkDate)
        for (let k = 0; k < dayTmpList.length; k++) {
          if (dayTmpList[k].ShiftType == 0) {
            dataList[i].D = _.cloneDeep(dayTmpList[k])
          }
          if (dayTmpList[k].ShiftType == 1) {
            dataList[i].N = _.cloneDeep(dayTmpList[k])
          }
        }
      }
      console.log(dataList, 'dataList')

      return this.checkDataFormat(dataList[0].WorkDate, dataList)
    },
    submit2() {
      this.submitLoading = true
      this.http.get(this.api + 'UpdateShift', this.data2)
        .then((r) => {
          this.editFormVisible2 = false
          this.submitLoading = false
          this.getList()
        })
        .catch((r) => {
          this.editFormVisible2 = false
          this.submitLoading = false
        })
    },
    submit() {
      let insertUrl = this.updateFlag ? this.api + 'GenerateCalendarDataUpdate' : this.api + 'GenerateCalendarData'                                                                   
      let url = this.data.id ? updateUrl : insertUrl
      let data = this.formatBeforeSave(this.data)
      let check = this.validataData(this.fields, data)
      if (!check) return
      this.submitLoading = true
      this.http
        .post(url, data)
        .then((r) => {
          this.editFormVisible = false
          this.getList()
          // 设置设备工作时间
          this.http.post(this.$api.Schedule + 'GetMachineClendar',
            {
              deviceIds:data?.deviceIds,
              StartTime:data?.StartTime,
              // EndTime:data?.EndTime,
              // 取data?.EndTime当天最后一秒
              EndTime: dayjs(data?.EndTime).endOf('day').format('YYYY-MM-DD HH:mm:ss'),
            }
          ).then((r) => {
          })
        })
        .finally(() => {
          this.submitLoading = false
        })
    },
    getList() {
      this.popupShow = false
      this.leftList = []
      this.rightList = []
      this.pageLoading = true
      let url = this.apiList || this.api + 'getlist'
      this.http.get(url, this.query)
        .then((r) => {
          this.list = this.formatList(r)
        })
        .finally(() => {
          this.pageLoading = false
        })
    },
    updateItem() {
      this.updateFlag = true
      this.editFormVisible = true
      let IsResult = this.fields.find(i => i.key == 'IsResult')
      let IsSkip = this.fields.find(i => i.key == 'IsSkip')
      let deviceIds = this.fields.find(i => i.key == 'deviceIds')
      let Weeks = this.fields.find(i => i.key == 'Weeks')
      IsResult.hidden = false
      IsSkip.hidden = true
      //deviceIds.hidden = true
      Weeks.hidden = true
    },
    beforeCheckedData(data) {
      let tmp = _.cloneDeep(data)
      tmp.StartTime = tmp.dataTime[0]
      tmp.EndTime = tmp.dataTime[1]
      tmp.ShiftType = (tmp.ShiftType - 1).toString()
      if (tmp.ShiftType == 2) {
        delete tmp.ShiftType
      }
      delete tmp.dataTime
      return tmp
    },
    submit3(data) {
      this.submitLoading = true
      this.http.get(
        `${this.$api.calendar}${this.actionsOverType == 1 ? 'APSLineIntermodulation' : 'DeleteMany'
        }`,
        this.beforeCheckedData(data),
        'post'
      )
        .then((r) => {
          this.editFormVisible3 = false
          this.submitLoading = false
          this.getList()
        })
        .catch((r) => {
          this.editFormVisible3 = false
          this.submitLoading = false
        })
    },
    // 右键展示菜单
    showPopup(type, item, day, event) {
      event.preventDefault()
      if (type == 0) {
        this.popup.top = event.pageY - event.offsetY - 70
      } else {
        this.popup.top = event.pageY - event.offsetY - 50
      }
      if (item && item.Id) {
        this.popupList.forEach((c) => {
          if (c.title == '新增') {
            c.ishaveDate = false
          } else {
            c.ishaveDate = true
          }
        })
      } else {
        this.popupList.forEach((c) => {
          if (c.title == '编辑' || c.title == '删除') {
            c.ishaveDate = false
          } else {
            c.ishaveDate = true
          }
        })
      }
      this.popup.left = event.pageX - event.offsetX - 70
      this.popupShow = true
      // console.log(this.popup.top, this.popup.left)
      this.popupType = type
      this.popupData = item
        ? item
        : {
          WorkDate: day,
        }
    },
    // 右边处理
    async calendarClickSelect(type) {
      switch (type) {
        case 1:
          this.editItem(this.row, this.calendarType)
          break
        case 2:
          this.data2.ShiftId = null
          this.data2.PlantCalendarId = this.row.PlantCalendarId
          this.submit2()
          break
      }
    },
    // 右键事件处理
    async popupClick(item) {
  
    },
    queryMouthChange(flag) {
      if (flag) {
        this.query.time = dayjs(this.query.time)
          .add(1, 'months')
          .format('YYYY-MM-DD')
      } else {
        this.query.time = dayjs(this.query.time)
          .add(-1, 'months')
          .format('YYYY-MM-DD')
      }
      this.getList()
    },
    topRightShowClick() {
      if (this.row.Id) {
        this.showRight = !this.showRight
      } else {
        this.$message.info('请选择一个班次')
      }
    },
  },
  created() {
    // this.getLineOptions()
    this.getForemanOptions()
  },
  mounted() {
    this.getList()
  },
}
</script>
<style lang="scss" scoped>
.app-container {
  overflow-x: hidden;
  overflow-y: auto;
  height: 100%;
}

.app-container::-webkit-scrollbar {
  width: 3px;
}

.topTitle {
  border: 1px solid #e4e4e4;
  padding: 38px 10px 10px;
  position: relative;
}

.topTitle .top-title {
  transition: all 0.5s;
  color: #666;
  background: #f1f1f1;
  height: 28px;
  line-height: 28px;
  position: absolute;
  width: 100%;
  left: -10px;
  font-size: 12px;
  font-weight: 500;
  padding-left: 20px;
  top: 0;
  left: 0;
  border-bottom: 1px solid #e4e4e4;
  // letter-spacing: 2px;
  z-index: 9;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.calendar {
  width: 100%;

  &_header {
    display: flex;
    width: 100%;

    .calendar_item {
      height: 40px;
      line-height: 40px;
      // background: #cacaca;
      border-color: #f1f1f1;
      color: #999;
      font-size: 16px;
    }

    // .calendar_item:nth-last-child(1),
    // .calendar_item:nth-last-child(2) {
    //   color: rgb(207, 71, 71);
    // }
  }

  &_main {
    display: flex;
    flex-wrap: wrap;
  }

  &_item {
    width: 14%;
    height: 110px;
    border: 1px solid #f1f1f1;
    text-align: center;
    cursor: pointer;
    position: relative;
    font-weight: bolder;

    &_base {
      position: relative;
      width: 100%;
      height: 100%;
      overflow: hidden;

      &_isHoliday {
        color: #f56c6c;
      }

      &_class {
        background: #fff;
        color: #78b9fb;
        height: 40px;
        position: relative;
        display: flex;
        justify-content: flex-end;
        align-items: center;

        div {
          width: 100%;
          line-height: 40px;
          transition: all 0.5s;
          white-space: nowrap;
        }

        .fa-icon {
          // padding: 10px;
          margin-right: 8px;
          width: auto;
          height: 40px;
          font-size: 18px;
        }
      }

      &_class:last-of-type {
        // background: rgba(49, 49, 49, 0.799);
        // color: rgb(198, 25, 25);
        color: #67c23a;
      }

      &_class:hover {
        background: rgba(64, 158, 255, 0.3);
        border: 1px dashed;
        // div:first-of-type {
        //   width: 80%;
        // }
      }

      &_class_isClick {
        // background: #67c23a !important;
      }
    }
  }
}

.popup-tooltip {
  position: absolute;
  width: 150px;
  min-height: 20px;
  border: 1px solid #ccc;
  z-index: 999;
  background: #fff;
  box-shadow: 5px 5px 10px 0 #999;

  &-item {
    height: 40px;
    line-height: 40px;
    padding-left: 20px;
    font-size: 16px;
    cursor: pointer;
  }

  &-item:hover {
    color: #fff;
    background: #265ece;
  }
}

::v-deep .filter-container .el-date-editor--month.el-input,
::v-deep .filter-container .el-date-editor--month.el-input__inner {
  width: 130px !important;
}
</style>
